<template>
  <div v-loading="pageLoading"
       v-loading.fullscreen.lock="pageLoading"
       element-loading-text="正在跳转新的运行实例...">
    <div v-if="$route.path == '/home/projectTwo'" style="float: right; height: 46px; line-height: 46px; margin-left: 5px;margin-right:5px;position: relative;" >
      <!-- <span class="toolsNameCss" style="" v-if="$route.query.pName">{{ '工具流名称：' + titleInfo }}</span>
      <span class="exampleNameCss" v-if="$route.query.pName">{{'实例名称：' + $route.query.pName}}</span>

      <span class="toolsNameCssNoPRName" v-if="!$route.query.pName">{{titleInfo}}</span> -->
      <el-breadcrumb style="height:100%;line-height:46px">
  <el-breadcrumb-item v-if="$route.query.pName">{{titleInfo}}</el-breadcrumb-item>
  <el-breadcrumb-item  v-if="$route.query.pName"> <span style=" font-weight: 550; !important">{{ $route.query.pName}}</span> </el-breadcrumb-item>
  <el-breadcrumb-item v-if="!$route.query.pName">{{titleInfo}}</el-breadcrumb-item>
</el-breadcrumb>
    </div>
    <div class="wrHd" style="min-width: 750px">
<!--      v-show="$route.path === '/home/project' && screenWidth >= 1065"-->
      <a @click="zoomOut()" title="缩小画布" v-show="$route.path === '/home/project'">
        <i class="fa fa-search-minus"></i>
      </a>
      <span id="zoomSize" class="zoomSize" v-show="$route.path === '/home/project'">{{ contentStyle.height }}%</span>
      <a @click="zoomIn()">
        <i class="fa fa-search-plus" title="放大画布" v-show="$route.path === '/home/project'"></i>
      </a>


<!--      <span class="gLine" v-if="this.$route.path === '/home/projectTwo'" v-show="screenWidth >= 1300"></span>-->
<!--      <a @click="createEngineeringExample" v-if="this.$route.path === '/home/projectTwo'" v-show="screenWidth >= 1300">-->

<!--      <span class="gLine" v-if="this.$route.path === '/home/project' || (this.$route.path === '/home/projectTwo' && !this.$route.query.id && !this.$route.query.rundId)" v-show="screenWidth >= 1300"></span>-->
      <span class="gLine" v-if="this.$route.path === '/home/project'" v-show="screenWidth >= 1300"></span>

      <a @click="createEngineeringExample" v-if=" this.$route.path === '/home/project' ||
      (this.$route.path === '/home/projectTwo' && !this.$route.query.id && !this.$route.query.rundId)" v-show="screenWidth >= 1300">
<!--        <i class="fa fa-edit" title="创建运行实例"/>-->
        <i class="fa fa-paper-plane" title="创建运行实例"/>
      </a>

      <span class="gLine"  v-if="this.$route.path === '/home/project' ||
      (this.$route.path === '/home/projectTwo' && !this.$route.query.id && !this.$route.query.rundId)" v-show="screenWidth >= 1300"></span>

      <a @click="saveFlow"  v-if="this.$route.path === '/home/project'" v-show="screenWidth >= 1300">
        <i class="fa fa-save" title="保存流程"></i>
      </a>

<!--      <span class="gLine" v-show="screenWidth >= 1300"></span>-->
      <a id="run" @click="play" v-if="this.$route.path === '/home/projectTwo' && !isRunning && !NewSwitch" v-show="screenWidth >= 1300">
        <i class="fa fa-play-circle" title="全部运行"></i>
      </a>

<!--      <a id="sptop" @click="stop" v-else-if="isRunning" v-show="screenWidth >= 1300">-->
<!--        <i-->
<!--          class="fa"-->
<!--          :class="isHover ? 'fa-stop-circle' : 'fa-spinner fa-spin'"-->
<!--          @mouseover="mouseover"-->
<!--          @mouseout="mouseout"-->
<!--          title="停止运行"-->
<!--        ></i>-->
<!--      </a>-->

<!--      <a id="run" @click="saveHistory" v-if="this.$route.path === '/home/projectTwo'" v-show="screenWidth >= 1300">-->
<!--        <i class="fa fa-save" title="历史数据保存"></i>-->
<!--      </a>-->

     <a style="width:50px" v-show="screenWidth >= 1300" v-if="!NewSwitch && isRunning">
       <el-button v-if="this.$route.path === '/home/projectTwo'" @click="handelCompleted" type="text" size="">执行完成</el-button></a>

<!--      {{NewSwitch}} false 自动  true  单步-->
      <a v-if="this.$route.path === '/home/projectTwo'" v-show="screenWidth >= 1300">
        <el-switch
          v-model="NewSwitch"
          active-color="#409eff"
          inactive-color="#409eff"
          @change="NewSwitchClick"
          active-text="单步"
          inactive-text="自动">
        </el-switch>
      </a>

<!--       <div v-if="$route.path == '/home/projectTwo'" style="float: right; height: 46px; line-height: 46px; margin-right: 30px">-->
      <!-- <el-button type="text" @click="syncFile">同步编辑态文件</el-button> -->

<!--      </div>-->





      <div style="float: left; height: 46px; line-height: 46px; margin-right: 5px;margin-left: 4px;" v-show="screenWidth >= 1000">
<!--        <el-button class="el-icon-refresh-left jumpBtnCss" @click="pageJump('2')"-->
<!--                   v-if="this.$route.path === '/home/project'"-->
<!--                   size="mini"-->
<!--                   :style="{backgroundColor:btnName === '工具运行' ? '#409eff' : '',color:btnName === '工具运行' ? 'white' : '' }">工具设计</el-button>-->

<!--        <el-button class="el-icon-refresh-left jumpBtnCss" @click="pageJump('2')"-->
<!--                   v-if="this.$route.path === '/home/project'"-->
<!--                   size="mini"-->
<!--                   :style="{backgroundColor:btnName === '工具设计' ? '#409eff' : '',color:btnName === '工具设计' ? 'white' : '' }">工具运行</el-button>-->

        <el-button class="el-icon-back jumpBtnCss" @click="pageJump('1')" size="mini"> 返回</el-button>
        <el-button v-if="this.$route.path === '/home/projectTwo' && !this.$route.query.fDesign" v-show="screenWidth >= 1300" class="el-icon-refresh" @click="resetButton()" size="mini"> 重置</el-button>

<!--        el-icon-s-tools-->
        <el-button class="jumpBtnCss" @click="pageJump('2','design')"
                   v-if="$route.query && $route.query.fDesign && $route.query.fDesign.toString() === 'true' "
                   size="mini"
                   :style="{backgroundColor:btnName === '调试运行' ? '#409eff' : '',color:btnName === '调试运行' ? 'white' : '' }"><i class="fa fa-pencil"></i> 工具设计</el-button>

<!--        el-icon-video-play-->
        <el-button class="jumpBtnCss" @click="pageJump('2','run')"
                   v-if="$route.query && $route.query.fDesign && $route.query.fDesign.toString() === 'true' "
                   size="mini"
                   :style="{backgroundColor:btnName === '工具设计' ? '#409eff' : '',color:btnName === '工具设计' ? 'white' : '' }"><i class="fa fa-bug"></i> 调试运行</el-button>


      </div>

    </div>
  </div>
</template>
<style>
</style>
<script>
import { mapGetters } from "vuex";
import {
  runInfomation,
  syncRunFile,
  saveHistoryList,
  createNewEngineeringExample,
  resetBtn,
  queryInstanceRunStatus,
  editOrAddInstanceRunStatus
} from "@/api/sourceDetail";
export default {
  name: "WorkHeader",
  props: ["titleInfo"],
  data() {
    return {
      syncFileStr: "",
      isHover: false,
      NewSwitch: this.$store.state.project.switchingVariable,
      btnName: "",

      screenWidth: document.body.clientWidth,
      pageLoading: false
    };
  },
  computed: {
    ...mapGetters(["httpServer", "permission"]),
    flowData: function() {
      return this.$store.state.project.flowData;
    },
    viewEditArea: function() {
      return this.$store.state.project.viewEditArea;
    },
    contentStyle: function() {
      return this.flowData.contentStyle;
    },
    isRunning: function() {
      return this.flowData.isRunning;
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.path.indexOf("projectTwo") >= 0) {
          this.btnName = "工具设计";
          document.title = this.$store.state.global.title + " - 运行";
        } else if (newVal.path.indexOf("project") >= 0) {
          this.btnName = "调试运行";
          document.title = this.$store.state.global.title + " - 工具设计";
        } else {
          document.title = this.$store.state.global.title;
        }

        if (newVal.name !== "ProjectTwo") return;
        this.syncFileStr = newVal.query.id;
      }
    },
    screenWidth(val) {
      // 使用定时器 避免频繁触发resize函数导致页面卡顿
      // if (!this.chartsTimer) {
      // 监听screenWidth值改变，重新赋值
      this.screenWidth = val;
      // console.log(this.screenWidth);
      // this.chartsTimer = true
      // setTimeout(() => {
      //   this.$nextTick(() => {
      //     this.drawCharts_round()
      //     // this.drawCharts_down()
      //   })
      //   this.chartsTimer = false
      // }, 200)
      // }
    }
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        // window.screenWidth = document.body.clientWidth
        // this.screenWidth = window.screenWidth
        this.screenWidth = document.body.clientWidth;
      })();
    };
  },
  methods: {
    //获取节点状态
    getNodeStatus(projectId, runId) {
      queryInstanceRunStatus(projectId, runId).then(res => {
        if (res.status === "SUCCESS") {
          this.$store.state.project.flowData.nodes &&
            this.$store.state.project.flowData.nodes.map(ele => {
              ele.runStyle = "status-disW";
            });
        }
      });
    },
    //重置按钮
    resetButton() {
      resetBtn(this.$route.query.id, this.$route.query.runId).then(res => {
        if (res.status === "SUCCESS") {
          this.$store.state.project.flowData.nodes &&
            this.$store.state.project.flowData.nodes.map(ele => {
              ele.runStyle = "status-disW";
            });
          this.updateRunStatusFunc();
        }
      });
    },
    updateRunStatusFunc() {
      if (
        this.$route.path == "/home/projectTwo" &&
        this.$route.query &&
        this.$route.query.runId
      ) {
      } else {
        console.log("不在运行实例页面不进行节点的状态保存!");
        return;
      }

      // console.log(JSON.parse(JSON.stringify(this.$store.state.project.flowData)));
      let allNodes = JSON.parse(
        JSON.stringify(this.$store.state.project.flowData.nodes)
      );
      let statusStr = [];
      allNodes &&
        allNodes.forEach(val => {
          statusStr.push(val.id + val.runStyle.substr(6, val.runStyle.length));
        });
      // console.log(statusStr.toString());
      queryInstanceRunStatus(
        this.$route.query.id,
        this.$route.query.runId
      ).then(res => {
        // console.log(res);
        if (res.status === "SUCCESS") {
          // status-disW
          // status-working
          // status-sus
          let data = {
            projectId: this.$route.query.id.toString(),
            instanceId: this.$route.query.runId.toString(),
            status: statusStr.toString()
          };
          // console.log(res);
          if (res.data && res.data[0] && res.data[0].status) {
            //存储过节点状态
            data["id"] = res.data[0].id;
            editOrAddInstanceRunStatus(data).then(item => {
              if (item.status === "SUCCESS") {
                console.log("节点运行状态存储成功！");
              } else {
                this.$notify.info("节点运行状态记录失败！");
              }
            });
          } else {
            //未存储过节点运行状态
            editOrAddInstanceRunStatus(data).then(item => {
              if (item.status === "SUCCESS") {
                console.log("节点运行状态存储成功！");
              } else {
                this.$notify.info("节点运行状态记录失败！");
              }
            });
          }
        }
      });
    },
    pageJump(num, what) {
      this.$store.state.project.flowData.nodes &&
        this.$store.state.project.flowData.nodes.map(val => {
          val.runStyle = "status-disW"; // 初始化 runStyle
        });
      if (num === "1") {
        // this.$router.go(-1)
        // this.$router.replace({path:'/home/main',params:{returnId:'1112',}})
        this.$router.push({
          name: "Main",
          params: { isFromPageReturn: "true" }
        });
      } else {
        // this.$route.path // "/home/project" 工具流设计   /home/projectTwo 运行
        // console.log(this.$route.path);

        if (this.$route.path == "/home/projectTwo") {
          //在运行页面
          if (
            this.$route.query &&
            this.$route.query.fDesign &&
            this.$route.query.fDesign.toString() === "true"
          ) {
            if (what === "design") {
              this.$router.replace(
                "/home/project?id=" + this.$route.query.id + "&fDesign=true"
              );
            }
          }

          // else {
          //   this.$router.replace("/home/project");
          // }
        } else if (this.$route.path == "/home/project") {
          //在设计页面
          if (
            this.$route.query &&
            this.$route.query.fDesign &&
            this.$route.query.fDesign.toString() === "true"
          ) {
            if (what === "run") {
              this.$router.replace(
                "/home/projectTwo?id=" + this.$route.query.id + "&fDesign=true"
              );
            }
          }
          // else {
          //   this.$router.replace("/home/projectTwo");
          // }
        }
      }
    },

    saveHistory() {
      saveHistoryList(this.syncFileStr).then(res => {
        console.log("%c 🍇 res", "color:#93c0a4", res);
        if (res.status == "SUCCESS") {
          this.$message.success("保存成功");
        }
      });
    },
    handelCompleted() {
      let getCurNodeId = localStorage.getItem("curNodeId");
      var curProjectItem = this.flowData.currentProjectDetail;
      if (curProjectItem.id) {
        this.runMethod({
          run: true,
          runIndex: 4,
          projectId: this.flowData.currentProjectDetail.id,
          componentId: getCurNodeId
        });
      } else {
        this.$notify({
          title: "提示",
          message: "请先选择工程！",
          type: "warning"
        });
      }
    },
    runMethod: function(args) {
      //运行方法
      if (this.flowData.isRunning) {
        this.$notify({
          message: "流程运行中，不允许该操作！",
          type: "warning"
        });
        return;
      }
      //更新运行状态为正在运行
      if (this.flowData.isRunning) {
        this.$store.commit("updateMenuProjectSelectComponent", ""); //更新右侧组件视图
        return;
      }
      //当前选中工程项
      this.$store.dispatch("checkNodeElements").then(checkResult => {
        if (checkResult.testResult) {
          //保存完成后 运行流程
          this.$store.dispatch("saveCurrentFlowJson", args);
        } else {
          this.$notify({
            message: checkResult.msg,
            type: "warning"
          });
        }
      });
    },
    NewSwitchClick(e) {
      this.$store.commit("changeSwitching", e);
    },
    /*
    syncFile() {
      syncRunFile(this.syncFileStr).then(res => {
        if (res.status == "SUCCESS") {
          runInfomation(this.syncFileStr).then(response => {
            if (response.status == "SUCCESS") {
              this.$store.state.project.flowData.currentProjectDetail =
                response.data;
              if (response.data.json) {
                this.$store.dispatch("fillCurrentJson", {
                  json: response.data.json
                });
              } else {
                this.$store.state.project.flowData.contentStyle.height = 120;
                this.$store.state.project.flowData.nodes = [];
                this.$store.state.project.flowData.links = [];
              }
              //切换完成
              this.$store.state.project.flowData.projectChange = false;
              this.$message.success("同步成功");
            }
          });
        }
      });
    },
    */
    zoomIn: function() {
      //拓展画布
      if (this.contentStyle.height <= 290) {
        this.contentStyle.height += 10;
      }
      var content = document.getElementById("dwaContent");
      content.style.zoom = this.flowData.contentStyle.height + "%";
    },
    zoomOut: function() {
      //缩小画布
      if (this.contentStyle.height > 100) {
        this.contentStyle.height -= 10;
      }
      var content = document.getElementById("dwaContent");
      var clientHeight = content.clientHeight;
      var scrollHeight = content.scrollHeight;
      console.log(clientHeight + "-" + scrollHeight);
      if (clientHeight < scrollHeight) {
        this.contentStyle.height += 10;
      }
      content.style.zoom = this.flowData.contentStyle.height + "%";
    },
    saveFlow: function() {
      //保存流程
      //当前选中工程项
      var curProjectItem = this.flowData.currentProjectDetail;
      if (curProjectItem.id) {
        this.saveCurrentFlowJson();
      } else {
        this.$notify({
          title: "提示",
          message: "请先选择工程！",
          type: "warning"
        });
      }
    },

    //运行状态下新增运行实例
    async createEngineeringExample() {
      // console.log(JSON.parse(JSON.stringify(this.flowData.currentProjectDetail.id)));
      // return
      this.$prompt("请输入新的运行实例名称", "提示", {
        confirmButtonText: "保存并创建",
        cancelButtonText: "取消"
        // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: '邮箱格式不正确'
      })
        .then(({ value }) => {
          if (value && value.trim() && value.trim().length >= 2) {
            this.saveCurrentFlowJson().then(res => {
              if (res == "保存成功") {
                createNewEngineeringExample(
                  this.flowData.currentProjectDetail.id,
                  value.trim()
                ).then(res => {
                  if (res.status === "SUCCESS" && res.data) {
                    this.$notify.success("实例创建成功！");
                    this.pageLoading = true;

                    let newQuery = {};
                    if (this.$route.query.isAuth) {
                      newQuery = {
                        id: this.flowData.currentProjectDetail.id,
                        runId: res.data,
                        pName: value.trim(),
                        isAuth: 1
                      };
                    } else {
                      newQuery = {
                        id: this.flowData.currentProjectDetail.id,
                        runId: res.data,
                        pName: value.trim()
                      };
                    }

                    setTimeout(() => {
                      this.$router.replace({
                        path: "/home/projectTwo",
                        query: newQuery
                      });
                      this.pageLoading = false;
                      // setTimeout(() => {
                      //   window.location.reload();
                      // }, 20);
                    }, 1800);

                    /////////////////////////////////////刷新table
                    /////////////////////////////////////刷新table
                    // if(row.isBeAuthorList || row.isBeAuthorProject){ //已参与项目（授权项目）
                    //   getHasAuthProjectList().then(res=>{
                    //     if(res.status === 'SUCCESS'){
                    //       // console.log("%c 🍐 res", "color:#ea7e5c", '已授权项目  >>>>>>>> ',JSON.parse(JSON.stringify(res)));
                    //       res.data && res.data.map(ele=>{
                    //         ele['isBeAuthorProject'] = true
                    //       })
                    //       // this.$emit("getInfoListVal", res.data);
                    //       this.getInfoListVal(res.data)
                    //     }
                    //   })
                    // }else{//一般工程 项目
                    //   // console.log(JSON.parse(JSON.stringify(row.parentId)));
                    //   project(row.parentId).then(res => {
                    //     this.getInfoListVal(res.data)
                    //   });
                    // }
                    /////////////////////////////////////刷新table
                    /////////////////////////////////////刷新table
                  }
                });
              } else {
                this.$message({
                  type: "error",
                  message: "保存流程失败！"
                });
              }
            });
          } else {
            this.$message({
              type: "info",
              message: "实例名称太短！"
            });
            return;
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
    },

    //同步流程json数据到服务端
    saveCurrentFlowJson: function() {
      return new Promise((resolve, reject) => {
        var that = this;
        var curProjectItem = that.flowData.currentProjectDetail;

        var data = {};
        var nodes = that.flowData.nodes;
        var links = that.flowData.links;
        var compType = this.$store.state.project.systemComponents[0].children;
        let array1 = [];
        let array2 = [];

        compType.forEach(item => {
          item.children.forEach(aItem => {
            nodes.forEach(bItem => {
              // if (bItem.fileParse && bItem.fileParse.length > 0) {
              //   bItem.fileParse.splice(bItem.fileParse.length - 1, 1);
              // }
              if (
                aItem.name == bItem.name &&
                (item.name == "分类" ||
                  item.name == "回归" ||
                  item.name == "聚类" ||
                  item.name == "时序模型")
              ) {
                array1.push(item.name);
                array2.push(bItem.name);
              }
            });
          });
        });

        // console.log(nodes);

        // (data["modelType"] = array1), (data["modelAlgorithm"] = array2);
        data["modelType"] = array1;
        data["modelAlgorithm"] = array2;
        data["style"] = that.flowData.contentStyle;
        data["nodes"] = nodes;
        data["links"] = links;

        // console.log(data)
        // return

        let formData = new FormData();
        formData.append("content", JSON.stringify(data));

        this.$.ajax({
          url: that.httpServer + "/api/project/" + curProjectItem.id,
          method: "post",
          data: formData,
          processData: false,
          contentType: false,
          beforeSend: function(xhr) {
            xhr.setRequestHeader("accessToken", localStorage.accessToken);
          },
          success: function(response) {
            that.$notify({
              title: "提示",
              message: "保存成功",
              type: "success"
            });
            resolve("保存成功");
          },
          error: function(response) {
            that.$store.commit("dealRequestError", response);
            reject("保存失败");
          }
        });
      });
    },
    play: function() {
      //全部运行
      //当前选中工程项
      var curProjectItem = this.flowData.currentProjectDetail;
      if (curProjectItem.id) {
        //更新运行状态为正在运行
        this.runMethod({
          run: true,
          runIndex: 1,
          projectId: curProjectItem.id
        });
      } else {
        this.$notify({
          title: "提示",
          message: "请先选择工程！",
          type: "warning"
        });
      }
    },
    stop: function() {
      //停止运行
      this.$store.dispatch("stopFlow");
    },
    mouseover: function() {
      if (this.isRunning) {
        this.isHover = true;
      }
    },
    mouseout: function() {
      if (this.isRunning) {
        this.isHover = false;
      }
    },
    runMethod: function(args) {
      //运行方法
      var that = this;
      try {
        this.$store.commit("updateMenuProjectSelectComponent", ""); //更新右侧组件视图
        //当前选中工程项
        this.$store.dispatch("checkNodeElements").then(checkResult => {
          console.log(checkResult);
          if (checkResult.testResult) {
            //保存完成后 运行流程
            this.$store.dispatch("saveCurrentFlowJson", args);
          } else {
            this.flowData.isRunning = false;
            this.$notify({
              title: "提示",
              message: checkResult.msg,
              type: "warning"
            });
          }
        });
      } catch (e) {
        that.flowData.isRunning = false;
      }
    }
  }
};
</script>
<style scoped>
/deep/ .el-switch__label {
  width: 40px;
}

.jumpBtnCss {
  margin-left: 2px !important;
  padding: 7px !important;
}
.toolsNameCss {
  display: inline-block;
  position: absolute;
  left: 0;
  top: 1px;
  height: 23px;
  line-height: 23px;
  width: 160px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.exampleNameCss {
  display: inline-block;
  position: absolute;
  left: 0;
  bottom: 1px;
  height: 23px;
  line-height: 23px;
  width: 160px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.toolsNameCssNoPRName {
  display: inline-block;
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translate(0, -50%);
  height: 23px;
  line-height: 23px;
  width: 160px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  /*background-color: violet;*/
}
</style>
